/*
* jwt
* */
const jwt = require('jsonwebtoken')
const JWT_SECRET = 'shared-secret'//密钥
const unlessPathList = ['/api/login','/public'];//指定不执行该中间件的路径
const {encrypt,decrypt} = require('../config/crypto')
// const util = require('util')
// const verify = util.promisify(jwt.verify) // 解密


//生成token
function generateToken(data = {name:'admin',id:1}){
    //expiresIn表示token失效时间，为数字时秒做单位，也可用字符串'1h''1d'表示一小时 一天
    return jwt.sign({userInfo:encrypt(JSON.stringify(data))}, JWT_SECRET, { expiresIn: '2h' });
}

//验证token
async function verifyToken(ctx, next) {
    let authorization = ctx.request.headers["authorization"];
    if(authorization){
        let token = authorization.split(" ")[1];
        let payload = jwt.verify(token,JWT_SECRET,(error,decoded)=>{
            let userInfo = decrypt(decoded['userInfo']);
            if(error){
                ctx.body = {
                    status:-1,
                    msg:"登陆失效"
                };
            }
            else{
                ctx.token_data = userInfo;
            }
        });
    }
    return await next();
}
module.exports = {
    verifyToken,JWT_SECRET,unlessPathList,generateToken
}